package com.ai5suoai.ams.service;

import com.ai5suoai.ams.entity.IToVo;
import com.ai5suoai.ams.web.vo.ToEntity;

import org.springframework.data.repository.CrudRepository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author chenzhenjia
 * @since 16/4/21
 */
public abstract class AbstractService<T extends IToVo<VO>, VO extends ToEntity<T>, ID extends
        Serializable> {

    abstract CrudRepository<T, ID> getRepository();

    public <S extends T> Iterable<S> save(Iterable<S> entities) {
        return getRepository().save(entities);
    }

    public <S extends T> S save(S entity) {
        return getRepository().save(entity);
    }

//    public T save(VO vo) {
//        return getRepository().save(vo.toEntity());
//    }

    public Iterable<T> saveAll(Iterable<VO> entities) {
        List<T> list = new ArrayList<T>(0);
        entities.forEach(vo -> list.add(vo.toEntity()));
        return getRepository().save(list);
    }

    public boolean delete(ID id) {
        if (!exists(id))
            return false;
        getRepository().delete(id);
        return !exists(id);
    }

    public void delete(T entity) {
        getRepository().delete(entity);
    }

    public void delete(T... entities) {
        getRepository().delete(Arrays.asList(entities));
    }

    public void delete(ID... id) {
        getRepository().delete(getRepository().findAll(Arrays.asList(id)));
    }

    public T findOne(ID id) {
        return getRepository().findOne(id);
    }

    public VO findById(ID id) {
        return findOne(id).toVo();
    }

    public Iterable<VO> findAll(Iterable<ID> ids) {
        List<VO> list = new ArrayList<VO>(0);
        getRepository().findAll(ids).forEach(t -> list.add(t.toVo()));
        return list;
    }

    public Iterable<T> findAll(ID... ids) {
        return getRepository().findAll(Arrays.asList(ids));
    }

    public long count() {
        return getRepository().count();
    }

    public boolean exists(ID id) {
        return getRepository().exists(id);
    }

}
